Euler Problem 54

In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:

High Card: Highest value card.
One Pair: Two cards of the same value.
Two Pairs: Two different pairs.
Three of a Kind: Three cards of the same value.
Straight: All cards are consecutive values.
Flush: All cards of the same suit.
Full House: Three of a kind and a pair.
Four of a Kind: Four cards of the same value.
Straight Flush: All cards are consecutive values of same suit.
Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.

The cards are valued in the order: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.

If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on.

The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner.

How many hands does Player 1 win?


In [2]:
from collections import Counter

# Poker hands are ranked as follows:
# high card < 1 pair < 2 pair < 3 of a kind < straight < flush
#           < full house < 4 of a kind < straight flush < royal flush


# scorehand(hand) Returns the signature of a hand (see below) 
# modified to account for flushes and straights.
#
# straight is scored as ((3,1,2), (a,b,c,d,e)) to place it between
# 3 of a kind and full house.
#
# flush is scored as ((3,1,3), (a,b,c,d,e)) to place it between
# straight and full house.
#
# straight flush is scored as ((5,), (a,b,c,d,e)) to place it
# above 4 of a kind ((4,1), (a,b)).
#
# royal flush is scored as ((6,),) to place it above straight flush.

def scorehand(hand):
    ranks = get_ranks(hand)
    signature = get_signature(ranks)
    straight = (signature[0][0] == 1 and is_straight(ranks))
    if is_flush(hand):
        if is_royal(ranks):
            return ((6,),)
        if straight:
            return ((5,), ranks)
        if signature < ((3,2),):
            return ((3,1,3), ranks)
    elif straight and signature < ((3,2),):
        return ((3,1,2), ranks)
    return signature

# Get the ranks of the cards and sort them in reverse order.
def get_ranks(hand):
    return sorted(map(rank, hand), reverse=True)

# The signature is an ordered pair of tuples describing the number of cards
# of each rank. The first tuple contains the frequencies, in descending order.
# The second tuple contains the corresponding ranks.
#
# 3 of a kind has a signature of the form ((3,1,1), (a,b,c))
# full house has a signature of the form ((3,2), (a,b))
# four of a kind has a signature of the form ((4,1), (a,b))
#
# Two poker hands can be compared by comparing their signatures, using the standard
# lexicographic ordering, unless one or both hands is a straight or a flush.

# 
def get_signature(ranks):
    pairs = sorted(((x,y) for y,x in Counter(ranks).items()), reverse=True)
    return (tuple(p[0] for p in pairs), tuple(p[1] for p in pairs))

# Returns the rank of a card as an integer
# (T = 10, J = 11, Q = 12, K = 13, A = 14)
def rank(card):
    ranks = '23456789TJQKA'
    for i, c in enumerate(ranks):
        if c == card[0]:
            return i + 2

# Returns True if the hand is a flush, False otherwise.
def is_flush(hand):
    return all(card[1] == hand[0][1] for card in hand)

# Returns True if the hand is a straight, False otherwise.
# A precondition is that the hand does not contain a pair.
def is_straight(ranks):
    return ranks[0] - ranks[4] == 4 or ranks == [14, 5, 4, 3, 2]

# Returns True if all cards are Royal (10, J, Q, K, A), False otherwise.
def is_royal(ranks):
    return min(ranks) >= 10


with open('data/p054_poker.txt', 'r') as f:
    count = 0
    for line in f.readlines():
        row = line.split()
        if scorehand(row[:5]) > scorehand(row[5:]):
            count += 1
    print(count)


376

In [ ]: